package com.aliyun;
/**
 * 阿里云OSS上传类
 */

import cn.hutool.core.bean.BeanUtil;
import com.aliyun.oss.ClientConfiguration;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.common.utils.IOUtils;
import com.aliyun.oss.model.AccessControlList;
import com.aliyun.oss.model.OSSObject;
import com.aliyun.oss.model.ObjectMetadata;
import lombok.Data;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;

import java.io.*;
import java.net.URL;
import java.util.Calendar;


@Configuration
@Data
public class OssUpload  {

	private  boolean oss=true;

	private int timeout=5000;

	private  String accessKeyId;

	private String accessKeySecret;

	private  String bucketName;

	private  String ossEndpoint;

	private  String url;

	@Autowired
	private OssUpload_Jiuyi ossUpload_jiuyi;

	@Autowired
	private OssUpload_Yalian ossUpload_yalian;

	@Autowired
	private OssUpload_Jxgy ossUpload_jxgy;


	@Profile("jiuyi")
	@Bean("ossUpload_Jiuyi_string")
	public void  ossUpload_Jiuyi(){
		BeanUtil.copyProperties(ossUpload_jiuyi,this);
		init();
	}

	@Profile("jxgy")
	@Bean("ossUpload_Jxgy_string")
	public void  ossUpload_Jxgy(){
		BeanUtil.copyProperties(ossUpload_jxgy,this);
		init();
	}


	@Profile("yalian")
	@Bean("ossUpload_Yalian_String")
	public void  ossUpload_Yalian(){
		BeanUtil.copyProperties(ossUpload_yalian,this);
		init();
	}





	
	

	
	private OSSClient ossClient;

	public OssUpload() {
	}

	/**
	 * OSS初始化
	 */
	public void init() {

		if (oss==false)
		{
			return;
		}
		ClientConfiguration conf = new ClientConfiguration();
		conf.setConnectionTimeout(timeout);
		conf.setMaxErrorRetry(10);
		ossClient = new OSSClient("http://" + ossEndpoint, accessKeyId, accessKeySecret, conf);
	}
	
	/**
	 * 获取文件的URL地址
	 * @param newFileName
	 * @return
	 */
	public  String getURL(final String newFileName) {
		// TODO Auto-generated method stub
        String url = "";
		AccessControlList accs = ossClient.getBucketAcl(bucketName);
		if (accs.getGrants().isEmpty()) {
			Calendar c = Calendar.getInstance();
			c.add(Calendar.HOUR_OF_DAY, 1);
			URL _url = ossClient.generatePresignedUrl(bucketName, newFileName, c.getTime());
			url = _url.getPath();
		} else {
			url = String.format("%s/%s",this.url, newFileName);
		}
		ossClient.shutdown();

		return url;
	}


	

	public void setBucketName(String bucketName) {
		this.bucketName = bucketName;
	}

	public void destroy() {
		ossClient.shutdown();
	}

	/**
	 * 指定的key是否存在
	 */
	public boolean isExist(String key) {
		key = genKey(key);
		return ossClient.doesObjectExist(bucketName, key);
	}

	/**
	 * 从OSS中获取文件输入流
	 */
	public InputStream getObjeInputStream(String key) {
		key = genKey(key);
		OSSObject obj = ossClient.getObject(bucketName, key);
		return obj.getObjectContent();
	}

	/**
	 * 将输入流下载存到指定的File文件中
	 */
	public void saveIsToFile(InputStream is, File file) {
		FileOutputStream fos = null;
		try {
			fos = new FileOutputStream(file);
			byte[] buffer = new byte[1024 * 10];
			int len = -1;
			while ((len = is.read(buffer)) != -1) {
				fos.write(buffer, 0, len);
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			IOUtils.safeClose(fos);
		}
	}

	/**
	 * 文件下载,以流的形式
	 */
	public void downObj(String key, File file) {
		key = genKey(key);
		InputStream is = getObjeInputStream(key);
		saveIsToFile(is, file);
	}

	/**
	 * 简单上传OSS文件
	 */
	public String upload(final String newFileName, final File uploadName) {
		if (oss==false)
		{
			return null;
		}
		try{
			new Thread(new Runnable() {

				@Override
				public void run() {

					ObjectMetadata meta = new ObjectMetadata();
					if (newFileName!=null)
					{
						if (newFileName.endsWith(".png"))
						{
							meta.setContentType("image/png");
						}
						else if (newFileName.endsWith(".jpg"))
						{
							meta.setContentType("image/jpg");
						}
						else if (newFileName.endsWith(".gif"))
						{
							meta.setContentType("image/gif");
						}
						else if (newFileName.endsWith(".apk"))
						{
							meta.setContentType("application/octet-stream");
						}
						else if (newFileName.endsWith(".mp3"))
						{
							meta.setContentType("audio/mp3");
						}
						else if (newFileName.endsWith(".mp4"))
						{
							meta.setContentType("video/mp4");
						}
					}

					String ossFile = genKey(newFileName);
					//System.out.println("ossFile:"+ossFile);
					ossClient.putObject(bucketName, ossFile, uploadName, meta);

				}
			}).start();

		}catch (Exception e){

		}
		return null;
	}

	/**
	 * 删除指定key
	 */
	public void delObj(String key) {
		ossClient.deleteObject(bucketName, key);
	}

	/**
	 * 处理key开头是/,返回开头没有/的key
	 */
	private String genKey(String key) {
		if (key != null) {
			key = key.replaceAll("\\\\", "/");
		}
		if (key.startsWith("."))
		{
			key = key.substring(1);
		}
		while (key != null && key.startsWith("/")) {
			key = key.substring(1);
		}

		return key;
	}




}
